package gazzera.node.sslserver;
import java.security.cert.*;
import java.util.*;

import javax.net.ssl.*;



class AcceptorTrustManager implements X509TrustManager
{
	private CertificateAcceptor acc = null;
	
	/* this is needed becouse in the check() methods i also need the socket, but i can't pass it
	   so i place them in a map Thread -> SSLSocket so i can se which ssl socket is mine by looking on the map with
	   my current thread.
	*/
	public Map<Thread, SSLSocket> currentsocket = new HashMap<Thread, SSLSocket>();
	
	
	public AcceptorTrustManager(CertificateAcceptor acc)
	{
		super();
		this.acc = acc;
	}
/*
	private void check(X509Certificate[] chain) throws CertificateEncodingException, CertificateException
	{
		try
		{
			System.out.println(chain);
			String md5 = SSLUtils.getMd5Cert( chain[0] );
			if (md5.equals("7476c40ee29e7356c9b1c0df60d6d609") || md5.equals("97e8ce8e73e21c50d3048ba7f640d34f"))
			{
				System.out.println("OK");
			}
			else
			{
				System.out.println("PEER SCONOSCIUTO: "+md5);
				throw new CertificateException("Unknown peer");
			}
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new CertificateException("NoSuchAlgorithmException", e);
		}
	}
*/
	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
	{
		if (chain.length != 1)
		{
			throw new CertificateException("Certificate chain not 1");
		}
		
		if(!acc.check(chain[0], currentsocket.get(Thread.currentThread())))
		{
			throw new CertificateException("Connection not accepted");
		}
		
	}

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
	{
		if (chain.length != 1)
		{
			throw new CertificateException("Certificate chain not 1");
		}

		if(!acc.check(chain[0], currentsocket.get(Thread.currentThread())))
		{
			throw new CertificateException("Connection not accepted");
		}

	}

	@Override
	public X509Certificate[] getAcceptedIssuers()
	{
		return new X509Certificate[]{};
	}

	
	
}
